package com.xzy.sms.web.system.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xzy.sms.web.domain.entity.User;
import com.xzy.sms.web.domain.service.UserService;
import com.xzy.sms.web.rest.RestObject;
import com.xzy.sms.web.system.utils.UserUtils;
import com.xzyframework.security.uitls.Passwords;

/**
 * 用户控制器
 * 
 * @author macong
 * @since 1.0
 * @version 2014-10-14 macong
 */
@Controller
@RequestMapping(value = "")
public class UserController {
    
    /** 日志打印器 */
    protected static Logger logger = LoggerFactory.getLogger(UserController.class);
    
    /** 配置项服务 */
    @Autowired
    private UserService userService;
    
    /**
     * 配置信息列表
     * 
     * @param modelMap 模型
     * @return 视图
     */
    @RequestMapping(value = "/admin/user")
    public String configList(ModelMap modelMap) {
        return "user/list";
    }
    
    /**
     * 配置信息列表分页
     * 
     * @param queryLike 查询条件
     * @param pageNumber 页数
     * @param pageSize 条数
     * @param model model
     * @return String
     */
    @RequestMapping(value = "/admin/user/page", method = { RequestMethod.GET, RequestMethod.POST })
    public String pageList(String queryLike, @RequestParam(defaultValue = "1") int pageNumber, 
    		@RequestParam(defaultValue = "20") int pageSize,
        ModelMap model) {
        Page<User> userList = userService.findByKeyword(queryLike, pageNumber, pageSize);
        model.put("userList", userList);
        return "user/_page";
    }
    
    /**
     * 用户详细信息
     * 
     * @param userId 用户id
     * @param model model
     * @return 视图
     */
    @RequestMapping(value = { "/admin/user/detail", "/user/detail" })
    public String userDetail(@RequestParam(required = false, value = "userId") String userId, ModelMap model) {
        if (!UserUtils.isAdmin()) {
            userId = UserUtils.getUserId();
        }
        
        if (StringUtils.isNotBlank(userId)) {
            model.put("user", userService.findUser(userId));
        }
        return "user/form";
    }
    
    /**
     * 用户详细信息
     * 
     * @param user 用户
     * @return 视图
     */
    @RequestMapping(value = { "/admin/user/save", "/user/save" })
    @ResponseBody
    public RestObject save(User user) {
        try {
            if (!UserUtils.isAdmin()) {
                user.setUserId(UserUtils.getUserId());
            }
            
            if (StringUtils.isEmpty(user.getUserId())) {
                // 是否存在相同的用户
                User u = userService.findByAccount(user.getAccount());
                if (u != null) {
                    return RestObject.newError("已经存在相同账号的用户");
                }
                
                // 如果是添加用户
                user.setPassword(Passwords.entryptPassword(user.getPassword()));
                
            } else if (StringUtils.isNotEmpty(user.getPassword())) {
                // 要修改用户密码
                String pass = Passwords.entryptPassword(user.getPassword());
                userService.updatePasswordById(pass, user.getUserId());
            }
            
            User newUser = userService.saveUser(user);
            return RestObject.newOk(newUser);
        } catch (Exception ex) {
            logger.error("保存用户信息时异常", ex);
            return RestObject.newError(ex.getMessage());
        }
    }
    
    /**
     * 用户详细信息
     * 
     * @param userId 用户id
     * @param model model
     * @return 视图
     */
    @RequestMapping(value = "/admin/user/del")
    @ResponseBody
    public RestObject del(String userId) {
        try {
            userService.deleteUser(userId);
            return RestObject.newOk("success");
        } catch (Exception ex) {
            logger.error("删除用户时异常", ex);
            return RestObject.newError(ex.getMessage());
        }
    }
    
    /**
     * 修改密码视图
     * 
     * @param userId 用户id
     * @param model model
     * @return 视图
     */
    @RequestMapping(value = "/user/changepassword")
    public String changePassword(String userId) {
        return "user/password";
    }
    
    /**
     * 用户详细信息
     * 
     * @param oldPassword x
     * @param password x
     * @return 视图
     */
    @RequestMapping(value = "/user/savepassword")
    @ResponseBody
    public RestObject savePassword(@RequestParam("old_password") String oldPassword, @RequestParam("new_password") String password) {
        try {
            String userId = UserUtils.getUserId();
            User user = userService.findCurrentUser();
            if (user == null) {
                return RestObject.newError("当前用户不存在");
            } else if (!Passwords.validatePassword(oldPassword, user.getPassword())) {
                return RestObject.newError("旧密码不正确");
            }
            userService.updatePasswordById(Passwords.entryptPassword(password), userId);
            return RestObject.newOk("success");
        } catch (Exception ex) {
            logger.error("删除用户时异常", ex);
            return RestObject.newError(ex.getMessage());
        }
    }
    
}
